<template>
  <div class="p-2">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目分类" prop="category">
          <el-select v-model="queryParams.category" placeholder="请选择项目分类" clearable style="width: 200px">
            <el-option v-for="dict in beauty_project_category" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="医院名称" prop="hospitalName">
          <el-input
            v-model="queryParams.hospitalName"
            placeholder="请输入医院名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="上架状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择上架状态" clearable style="width: 200px">
            <el-option v-for="dict in beauty_project_status" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['beauty:project:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['beauty:project:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['beauty:project:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Upload"
            :disabled="multiple"
            @click="handleBatchOnline"
            v-hasPermi="['beauty:project:online']"
          >批量上架</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            :disabled="multiple"
            @click="handleBatchOffline"
            v-hasPermi="['beauty:project:offline']"
          >批量下架</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['beauty:project:export']"
          >导出</el-button>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="projectList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
<!--        <el-table-column label="项目ID" align="center" prop="projectId" width="100" />-->
        <el-table-column label="项目主图" align="center" prop="image" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.image" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="projectName" width="200" show-overflow-tooltip />
        <el-table-column label="项目分类" align="center" prop="category" width="100">
          <template #default="scope">
            <dict-tag :options="beauty_project_category" :value="scope.row.category" />
          </template>
        </el-table-column>
        <el-table-column label="价格" align="center" prop="price" width="100">
          <template #default="scope">
            <span class="text-red-500">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="原价" align="center" prop="originalPrice" width="100">
          <template #default="scope">
            <span class="text-gray-400">¥{{ scope.row.originalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="医院名称" align="center" prop="hospitalName" width="200" show-overflow-tooltip />
        <el-table-column label="销量" align="center" prop="salesCount" width="80" />
        <el-table-column label="上架状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="beauty_project_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="" align="center" min-width="1" />
        <el-table-column label="操作" align="center" fixed="right" width="280">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="View"
              @click="handleDetail(scope.row)"
              v-hasPermi="['beauty:project:query']"
            >详情</el-button>
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['beauty:project:edit']"
            >修改</el-button>
            <el-button
              v-if="scope.row.status !== '0'"
              link
              type="success"
              @click="handleOnline(scope.row)"
              v-hasPermi="['beauty:project:online']"
            >上架</el-button>
            <el-button
              v-else
              link
              type="warning"
              @click="handleOffline(scope.row)"
              v-hasPermi="['beauty:project:offline']"
            >下架</el-button>
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['beauty:project:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="projectFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择项目分类" style="width: 100%">
                <el-option v-for="dict in beauty_project_category" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="form.price"
                :precision="2"
                :step="10"
                :min="0"
                style="width: 100%"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input-number
                v-model="form.originalPrice"
                :precision="2"
                :step="10"
                :min="0"
                style="width: 100%"
                placeholder="请输入原价"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 逾期费率配置 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="逾期费用类型" prop="overdueFeeType">
              <el-select v-model="form.overdueFeeType" placeholder="请选择逾期费用类型" style="width: 100%">
                <el-option label="按比例" value="1" />
                <el-option label="固定金额" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="逾期费率/金额" prop="overdueFeeRate">
              <el-input-number
                v-model="form.overdueFeeRate"
                :precision="4"
                :step="0.0001"
                :min="0"
                style="width: 100%"
                :placeholder="form.overdueFeeType === '1' ? '如0.0005表示0.05%/天' : '如10.00表示10元/天'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-alert
              :title="form.overdueFeeType === '1' ? '按比例：逾期费用 = 未还金额 × 费率 × 逾期天数（例如：0.0005 = 每日0.05%）' : '固定金额：逾期费用 = 固定金额 × 逾期天数（例如：10.00 = 每日10元）'"
              type="info"
              :closable="false"
              show-icon
              style="margin-bottom: 20px"
            />
          </el-col>
        </el-row>

        <!-- 医院多选 -->
        <el-form-item label="关联医院">
          <el-select
            v-model="selectedHospitals"
            multiple
            placeholder="请选择关联医院"
            style="width: 100%"
            clearable
            filterable
          >
            <el-option
              v-for="hospital in hospitalList"
              :key="hospital.hospitalId"
              :label="hospital.hospitalName"
              :value="hospital.hospitalId"
            >
              <span>{{ hospital.hospitalName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ hospital.city }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上架状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in beauty_project_status" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="项目标签" prop="tags">
          <el-input v-model="form.tags" placeholder="请输入项目标签，多个标签用逗号分隔" />
        </el-form-item>

        <el-form-item label="项目简介" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入项目简介" />
        </el-form-item>

        <el-form-item label="项目详情" prop="detail">
          <el-input v-model="form.detail" type="textarea" :rows="4" placeholder="请输入项目详情" />
        </el-form-item>

        <el-form-item label="项目主图" prop="image">
          <image-upload v-model="form.image" :limit="1" />
        </el-form-item>

        <el-form-item label="项目图片" prop="images">
          <image-upload v-model="form.images" :limit="5" />
        </el-form-item>

        <!-- 分期方案管理 -->
        <el-form-item label="分期方案">
          <el-button type="primary" size="small" @click="addInstallmentPlan">添加分期方案</el-button>
        </el-form-item>

        <el-table v-if="installmentPlans.length > 0" :data="installmentPlans" border style="width: 100%; margin-top: 10px">
          <el-table-column label="期数" width="120">
            <template #default="scope">
              <el-input-number v-model="scope.row.periods" :min="1" :max="36" size="small" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="月利率(%)" width="150">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.interestRate"
                :min="0"
                :max="1"
                :precision="4"
                :step="0.001"
                size="small"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="服务费率(%)" width="150">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.serviceFeeRate"
                :min="0"
                :max="1"
                :precision="4"
                :step="0.001"
                size="small"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="推荐" width="100" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.isRecommend" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="scope">
              <el-button type="danger" size="small" link @click="removeInstallmentPlan(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="项目详情" v-model="detailDialog.visible" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="项目ID">{{ detailDialog.data.projectId }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ detailDialog.data.projectName }}</el-descriptions-item>
        <el-descriptions-item label="项目分类">
          <dict-tag :options="beauty_project_category" :value="detailDialog.data.category" />
        </el-descriptions-item>
        <el-descriptions-item label="上架状态">
          <dict-tag :options="beauty_project_status" :value="detailDialog.data.status" />
        </el-descriptions-item>
        <el-descriptions-item label="价格">
          <span class="text-red-500 font-bold">¥{{ detailDialog.data.price }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="原价">
          <span class="text-gray-400">¥{{ detailDialog.data.originalPrice }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="销量">{{ detailDialog.data.salesCount }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ detailDialog.data.sortOrder }}</el-descriptions-item>
        <el-descriptions-item label="医院名称" :span="2">{{ detailDialog.data.hospitalName }}</el-descriptions-item>
        <el-descriptions-item label="医院地址" :span="2">{{ detailDialog.data.hospitalAddress }}</el-descriptions-item>
        <el-descriptions-item label="医院电话" :span="2">{{ detailDialog.data.hospitalPhone }}</el-descriptions-item>
        <el-descriptions-item label="项目标签" :span="2">
          <el-tag v-for="(tag, index) in detailDialog.data.tagList" :key="index" class="mr-2">{{ tag }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="项目简介" :span="2">{{ detailDialog.data.description }}</el-descriptions-item>
        <el-descriptions-item label="项目详情" :span="2">{{ detailDialog.data.detail }}</el-descriptions-item>
        <el-descriptions-item label="项目图片" :span="2">
          <div class="flex flex-wrap gap-2">
            <el-image
              v-for="(img, index) in detailDialog.data.imageList"
              :key="index"
              :src="img"
              :preview-src-list="detailDialog.data.imageList"
              fit="cover"
              style="width: 100px; height: 100px"
            />
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailDialog.data.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="BeautyProject">
import { ref, reactive, getCurrentInstance } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import { ElForm, ElMessageBox, ElMessage } from 'element-plus';
import ImageUpload from '@/components/ImageUpload/index.vue';
import {
  listProject,
  getProject,
  addProject,
  updateProject,
  delProject,
  onlineProject,
  offlineProject,
  batchOnlineProject,
  batchOfflineProject,
  exportProject,
  getProjectHospitals,
  getProjectInstallmentPlans
} from '@/api/beauty/project';
import type { ProjectQuery, ProjectVO, ProjectForm } from '@/api/beauty/project';
import { listHospital } from '@/api/beauty/hospital';
import type { HospitalVO } from '@/api/beauty/hospital';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { beauty_project_category, beauty_project_status } = toRefs<any>(proxy?.useDict('beauty_project_category', 'beauty_project_status'));

const loading = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const projectList = ref<ProjectVO[]>([]);

const queryFormRef = ref<InstanceType<typeof ElForm>>();
const projectFormRef = ref<InstanceType<typeof ElForm>>();

const queryParams = ref<ProjectQuery>({
  pageNum: 1,
  pageSize: 10,
  projectName: undefined,
  category: undefined,
  hospitalName: undefined,
  status: undefined
});

const dialog = reactive({
  visible: false,
  title: ''
});

const detailDialog = reactive({
  visible: false,
  data: {} as ProjectVO
});

// 医院列表
const hospitalList = ref<HospitalVO[]>([]);
const selectedHospitals = ref<number[]>([]);

// 分期方案接口定义
interface InstallmentPlan {
  periods: number;
  interestRate: number;
  serviceFeeRate: number;
  isRecommend: boolean;
}

// 分期方案列表
const installmentPlans = ref<InstallmentPlan[]>([]);

const form = ref<ProjectForm>({
  projectName: '',
  category: '',
  price: 0,
  originalPrice: 0,
  description: '',
  detail: '',
  image: '',
  images: '',
  tags: '',
  sortOrder: 0,
  status: '0'
});

const rules = reactive({
  projectName: [
    { required: true, message: '项目名称不能为空', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '项目分类不能为空', trigger: 'change' }
  ],
  price: [
    { required: true, message: '价格不能为空', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '项目简介不能为空', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '项目主图不能为空', trigger: 'blur' }
  ]
});

// 查询项目列表
function getList() {
  loading.value = true;
  listProject(queryParams.value).then((response: any) => {
    projectList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: ProjectVO[]) {
  ids.value = selection.map(item => item.projectId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 加载医院列表
function loadHospitalList() {
  listHospital({ pageNum: 1, pageSize: 999, status: '0' }).then((response: any) => {
    hospitalList.value = response.rows || [];
  });
}

// 添加分期方案
function addInstallmentPlan() {
  installmentPlans.value.push({
    periods: 3,
    interestRate: 0.008,
    serviceFeeRate: 0,
    isRecommend: false
  });
}

// 删除分期方案
function removeInstallmentPlan(index: number) {
  installmentPlans.value.splice(index, 1);
}

// 新增按钮操作
function handleAdd() {
  reset();
  loadHospitalList();
  selectedHospitals.value = [];
  installmentPlans.value = [];
  dialog.visible = true;
  dialog.title = '添加项目';
}

// 修改按钮操作
function handleUpdate(row?: ProjectVO) {
  reset();
  loadHospitalList();
  const projectId = row?.projectId || ids.value[0];

  // 加载项目基本信息
  getProject(projectId).then((response: any) => {
    form.value = response.data;
    dialog.visible = true;
    dialog.title = '修改项目';
  });

  // 加载项目关联的医院
  getProjectHospitals(projectId).then((response: any) => {
    selectedHospitals.value = response.data || [];
  });

  // 加载项目的分期方案
  getProjectInstallmentPlans(projectId).then((response: any) => {
    const plans = response.data || [];
    installmentPlans.value = plans.map((plan: any) => ({
      periods: plan.periods,
      interestRate: plan.interestRate,
      serviceFeeRate: plan.serviceFeeRate,
      isRecommend: plan.isRecommend === 1
    }));
  });
}

// 详情按钮操作
function handleDetail(row: ProjectVO) {
  getProject(row.projectId).then((response: any) => {
    detailDialog.data = response.data;
    detailDialog.visible = true;
  });
}

// 提交按钮
function submitForm() {
  projectFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 组装提交数据，包含医院和分期方案
      const submitData = {
        ...form.value,
        hospitalIds: selectedHospitals.value,
        installmentPlans: installmentPlans.value
      };

      if (form.value.projectId) {
        updateProject(submitData).then(() => {
          ElMessage.success('修改成功');
          dialog.visible = false;
          getList();
        });
      } else {
        addProject(submitData).then(() => {
          ElMessage.success('新增成功');
          dialog.visible = false;
          getList();
        });
      }
    }
  });
}

// 取消按钮
function cancel() {
  dialog.visible = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    projectName: '',
    category: '',
    price: 0,
    originalPrice: 0,
    description: '',
    detail: '',
    image: '',
    images: '',
    tags: '',
    sortOrder: 0,
    status: '0',
    overdueFeeRate: 0.0005,  // 默认0.05%/天
    overdueFeeType: '1'      // 默认按比例
  };
  selectedHospitals.value = [];
  installmentPlans.value = [];
  projectFormRef.value?.resetFields();
}

// 删除按钮操作
function handleDelete(row?: ProjectVO) {
  const projectIds = row?.projectId ? [row.projectId] : ids.value;
  ElMessageBox.confirm('是否确认删除项目编号为"' + projectIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return delProject(projectIds);
  }).then(() => {
    getList();
    ElMessage.success('删除成功');
  });
}

// 上架项目
function handleOnline(row: ProjectVO) {
  ElMessageBox.confirm('确认要上架项目"' + row.projectName + '"吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    return onlineProject(row.projectId);
  }).then(() => {
    getList();
    ElMessage.success('上架成功');
  });
}

// 下架项目
function handleOffline(row: ProjectVO) {
  ElMessageBox.confirm('确认要下架项目"' + row.projectName + '"吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return offlineProject(row.projectId);
  }).then(() => {
    getList();
    ElMessage.success('下架成功');
  });
}

// 批量上架
function handleBatchOnline() {
  ElMessageBox.confirm('确认要批量上架选中的项目吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    return batchOnlineProject(ids.value);
  }).then(() => {
    getList();
    ElMessage.success('批量上架成功');
  });
}

// 批量下架
function handleBatchOffline() {
  ElMessageBox.confirm('确认要批量下架选中的项目吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return batchOfflineProject(ids.value);
  }).then(() => {
    getList();
    ElMessage.success('批量下架成功');
  });
}

// 导出按钮操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有项目数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return exportProject(queryParams.value);
  }).then((response: any) => {
    // 创建下载链接
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '美容项目数据_' + new Date().getTime() + '.xlsx';
    link.click();
    window.URL.revokeObjectURL(url);
    ElMessage.success('导出成功');
  });
}

getList();
</script>

<style scoped>
.text-red-500 {
  color: #f56c6c;
}

.text-gray-400 {
  color: #909399;
}

.font-bold {
  font-weight: bold;
}

.mr-2 {
  margin-right: 8px;
}

.flex {
  display: flex;
}

.flex-wrap {
  flex-wrap: wrap;
}

.gap-2 {
  gap: 8px;
}
</style>
